//
//  GroupMuteVC.swift
//  YueChat
//
//  Created by 1 on 2024/11/1.
//

import UIKit

class GroupMuteVC: BaseVC {
    var group = DMCCGroup()
    var addGroupArray : Array<Any> = []
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getManagerList()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        title = "群禁言"
        setup()
        
    }
    
    @objc func onGroupRefreshChanged () {
        guard let groupInfo = gosnGroup.getGroupInfo(group.groupId) else {
            return
        }
        self.group = groupInfo
        self.tableView.reloadData()
    }
    
    init(group: DMCCGroup = DMCCGroup()) {
        super.init(nibName: nil, bundle: nil)
        self.group = group
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    func setup () {

        tableView.dataSource = self
        tableView.delegate = self
        
        if #available(iOS 15.0, *) {
            tableView.sectionHeaderTopPadding = 0
            tableView.sectionFooterHeight = 0
        }
        
        tableView.register(UINib(nibName: "SwitchCell", bundle: nil), forCellReuseIdentifier: "SwitchCell")
        tableView.register(UINib(nibName: "UserCell", bundle: nil), forCellReuseIdentifier: "UserCell")
    }
    
    func getManagerList () {
        dataSource.removeAll()
        let list = gosnMember.getMemberList(group.groupId, 0, group.memberCount)
        list.forEach { member in
            if member.mute == 1 {
                dataSource.append(member)
            }
        }
        
//        dataSource = gosnGroup.getGroupAdmins(group.groupId)
        
        tableView.reloadData()
    }
  
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                return 50
            }else {
                return 44
            }
        }else if indexPath.section == 1 {
            return 50
        }
        
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        if section == 0 {
            return 2
        }else if section == 1 {
            return 1
        }
        
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if(section == 1) || section == 0 {
            return 10
        }

        if dataSource.count > 0 {
            return 30;
        }
        return 0;
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 2 {
            let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 30))
    //        view.backgroundColor = UIColor.lightGray
            let label = UILabel(frame: CGRect(x: 17, y: 0, width: 100, height: 30))
            label.font = UIFont.systemFont(ofSize: 14)
            label.text = "禁言名单"
            
            if dataSource.count > 0 {
                view.addSubview(label)
            }

            return view
        }
        return UIView()
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
        if indexPath.section == 0 {
            if indexPath.row == 0 {
                let cell = tableView.dequeueReusableCell(withIdentifier: "SwitchCell", for: indexPath) as! SwitchCell
                cell.titleLab.text = "全员禁言"
                cell.type = .AllMute
                cell.group = group
                cell.sw.setOn(group.mute == 1 ? true : false, animated: false)
                return cell
            }else {
                let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
                cell.contentView.backgroundColor = UIColor.clear
                cell.accessoryType = .none
                cell.textLabel?.text = "全员禁言启用后，只允许群主和管理员发言。"
                cell.textLabel?.font = UIFont.systemFont(ofSize: 14)
                cell.textLabel?.textColor = UIColor.init(hex: 0xC0C0C0)
                return cell
            }
            
        }
        
        
        if indexPath.section == 1 {
            let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
            cell.contentView.backgroundColor = UIColor.clear
            cell.accessoryType = .disclosureIndicator
            cell.textLabel?.text = "群成员禁言"
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "UserCell", for: indexPath) as! UserCell
        let member = dataSource[indexPath.row] as! DMCCMember
        let user = gosnUser.getUserInfoDefault(member.memberId)
        cell.setUserInfo(userInfo: user)
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
//        let array = self.dataSource[indexPath.section] as! Array<String>
//        let name = array[indexPath.row]
        
        if indexPath.section == 1 {
            navigationController?.pushViewController(SetManagerVC(group: group, type: .Mute), animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
        
        if indexPath.section == 2 {
            return true
        }
        return false
    }

    func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
        let action = UITableViewRowAction(style: .default, title: "移出") { [self] (action, indexPath) in
            // 删除操作的处理
            removeUserItem(at: indexPath)
        }
        return [action]
    }
    
    func removeUserItem(at indexPath: IndexPath) {
        guard let member = dataSource[indexPath.row] as? DMCCMember else { return }
        
        
        MHAlert.showLoading()
        
        Task{
            let res = await gosnGroup.muteMembers(group.groupId, [member.memberId], false)
                    await MainActor.run {
                        if res{
                            MHAlert.showMessage(KLocalizedString("AlertLoadSuccess"))
//                            getManagerList()
                            dataSource.remove(at: indexPath.row)
                            tableView.reloadData()
                        }else{
                            MHAlert.showMessage(KLocalizedString("AlertOpearFail"))
                        }
                    }
                }
    }
    
    deinit {
        
    }

}
